package net.mksat.gan.keysmanager.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import net.mksat.gan.keysmanager.activities.EntryActivity;
import net.mksat.gan.keysmanager.database.DbAdapter;
import net.mksat.gan.keysmanager.util.BitmapUtil;
import ua.edu.nuos.androidtraining2013.kms.api.APIConstants;
import ua.edu.nuos.androidtraining2013.kms.dto.CatalogContainer;
import ua.edu.nuos.androidtraining2013.kms.dto.PersonnelContainer;

import java.io.*;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import static net.mksat.gan.keysmanager.connection.ServerConnection.connectionParser;
import static net.mksat.gan.keysmanager.connection.ServerConnection.downloadFile;

/**
 * Created by Serega on 07.07.2014.
 */
public class KMService extends Service {

    private static final String LOG_TAG = "KMService";
    private static DbAdapter dbAdapter;
    private BindConnect binder = new BindConnect();

    private static final String HTTP_URL_CATALOG = APIConstants.REST_CLIENT_URL + APIConstants.CLIENT_CTRL_CATALOG;
    private static final String HTTP_URL_PERSONNEL_PHOTO = APIConstants.REST_CLIENT_URL + APIConstants.CLIENT_CTRL_PERSONNEL_PHOTO;


    public static final String SAVE = "keys_manager";
    public static final String KEY_INSTRUCTION = "instruction";
    public static final String KEY_SPREADSHEET_URL = "spreadsheet_URL";

    SharedPreferences sPref;

    public DbAdapter getDbAdapter() {
        return dbAdapter;
    }

    WeakReference<EntryActivity> activity;

    public void onCreate() {
        super.onCreate();
        dbAdapter = new DbAdapter(getApplicationContext());
        Log.d(LOG_TAG, "Service onCreate");
    }

    public void updateDb(EntryActivity activity) {
        this.activity = new WeakReference<EntryActivity>(activity);
        CheckConnection conn = new CheckConnection();
        conn.execute();
    }

    public IBinder onBind(Intent intent) {
        Log.d(LOG_TAG, "Service onBind");
        return binder;
    }

    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.d(LOG_TAG, "Service onRebind");
    }

    public boolean onUnbind(Intent intent) {
        Log.d(LOG_TAG, "Service onUnbind");
        return super.onUnbind(intent);
    }

    public void onDestroy() {
        super.onDestroy();
        dbAdapter.close();
        Log.d(LOG_TAG, "Service onDestroy");
    }

    public class BindConnect extends Binder {
        public KMService getService() {
            return KMService.this;
        }
    }

    private class CheckConnection extends AsyncTask<Boolean, Boolean, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(Boolean... params) {
            try {
                CatalogContainer catalog = connectionParser(HTTP_URL_CATALOG);
                sPref = getSharedPreferences(SAVE, MODE_PRIVATE);
                sPref.edit().putString(KEY_INSTRUCTION, catalog.getInstructionText()).
                        putString(KEY_SPREADSHEET_URL, catalog.getSpreadsheetURL()).commit();
                dbAdapter.update(catalog);
                savePersonnelPhoto(catalog.getPersonnelList());

            } catch (IOException e) {
                return false;
            }
            return true;
        }

        @Override // from AsyncTask
        protected void onPostExecute(Boolean result) {
            if (activity.get() != null)
                activity.get().resetResult(result);
            super.onPostExecute(result);
        }

        private void savePersonnelPhoto(List<PersonnelContainer> personnelContainers) throws IOException {
            BitmapUtil bitmapUtil = new BitmapUtil();
            for (PersonnelContainer pc : personnelContainers) {
                long id = pc.getId();
                File tempFile = File.createTempFile("photo", null);
                URL url = new URL(HTTP_URL_PERSONNEL_PHOTO + "/" + id);
                URLConnection connection = url.openConnection();
                if (downloadFile((HttpURLConnection) connection, tempFile)) { // если файл с таким именем есть на сервере
                    File photoFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), String.valueOf(id));
                    bitmapUtil.convertBitmap(tempFile.getAbsolutePath(), photoFile.getAbsolutePath());
                }
                tempFile.delete();
            }
        }
        private void savePersonnelOrderScreen(){

        }
    }


}
